package constant.milk.cashbook.category;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.NameActivity;
import constant.milk.cashbook.bean.CategoryMainData;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkTextView;
import constant.milk.cashbook.util.MilkUtil;

public class CategoryInsertActivity extends SuperActivity
{
	private static final int NAME_REQUEST_CODE = 0;
	private static final int SUB_CATEGORY_REQUEST_CODE = 1;
	
	private View nameView;
	private View subCategoryView;
	
	private TextView nameTextView;
	
	private ListView listView;
	
	private Button saveButton;
	
	private ArrayList<String> list;
	
	private SubCategoryListAdapter adapter;
	
	private String subName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.category_insert_activity);
		
		setTitle("카테고리추가");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		nameView = findViewById(R.id.categoryInsertNameView);
		subCategoryView = findViewById(R.id.categoryInsertSubView);
		
		nameTextView = (TextView) findViewById(R.id.categoryInsertNameTextView);
		
		listView = (ListView) findViewById(R.id.listView);
		
		saveButton = (Button) findViewById(R.id.saveButton);
	}

	@Override
	protected void setOnClick()
	{
		nameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, NameActivity.class);
				intent.putExtra(NameActivity.NAME_DATA, nameTextView.getText().toString());
				startActivityForResult(intent, NAME_REQUEST_CODE);
			}
		});
		
		subCategoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, NameActivity.class);
				intent.putExtra(NameActivity.NAME_DATA, "");
				startActivityForResult(intent, SUB_CATEGORY_REQUEST_CODE);
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setCheckData())
				{
					return;
				}
				
				if (setSaveData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 저장에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		list = new ArrayList<String>();
		
		listView.setOnItemClickListener(onItemClickListener);
		
		adapter = new SubCategoryListAdapter(
				superContext, R.layout.normal_list_item, list);
		listView.setAdapter(adapter);
	}
	
	/**
	 * 테이터가 제대로 있는지 확인한다.
	 */
	private boolean setCheckData()
	{
		String name = nameTextView.getText().toString();
		
		if (name.equals("") || name.length() < 1)
		{
			MilkUtil.showDialog(superContext, "확인", "이름을 입력해주세요.");
			return true;
		}
		
		if (list.size() < 1)
		{
			MilkUtil.showDialog(superContext, "확인", "서브 카테고리를 추가해주세요.");
			return true;
		}
		
		return false;
	}
	
	private boolean setSaveData()
	{
		DbInsertQuery query = null;
		
		try
		{
			query = new DbInsertQuery(superContext, superDb);
			DBSelectQuery selectQuery = new DBSelectQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", nameTextView.getText().toString());
			map.put("count", "0");
			
			query.setCategoryMain(map);
			
			CategoryMainData data = selectQuery.getCategoryMainName(nameTextView.getText().toString());
			
			for (int i = 0; i < list.size(); i++)
			{
				map.clear();
				map.put("name", list.get(i));
				map.put("count", "0");
				map.put("linkid", data.getId());
				
				query.setCategorySub(map);
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == NAME_REQUEST_CODE)
		{
			String str = data.getStringExtra(NameActivity.NAME_DATA);
			
			DBSelectQuery query = new DBSelectQuery(superContext, superDb);
			
			int count = query.getCategoryMainCount(str);
			
			if (count > 0)
			{
				MilkUtil.showToast(superContext, "같은 이름의 메인 카테고리가 있습니다.");
				nameTextView.setText("");
				return;
			}
			
			nameTextView.setText(str);
		}
		else if (requestCode == SUB_CATEGORY_REQUEST_CODE)
		{
			String str = data.getStringExtra(NameActivity.NAME_DATA);
			
			for (int i = 0; i < list.size(); i++)
			{
				if (list.get(i).equals(str))
				{
					MilkUtil.showToast(superContext, "같은 이름의 서브 카테고리가 있습니다.");
					return;
				}
			}
			
			list.add(str);
			adapter.notifyDataSetChanged();
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			subName = (String) arg0.getItemAtPosition(position);
			
			MilkUtil.showSelectDialog(superContext, "확인", "서브 카테고리를 제거 하시겠습니까?", 
					new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					list.remove(subName);
					list.trimToSize();
					adapter.notifyDataSetChanged();
				}
			});
		}
	};
	
	/**
	 * 리스트 아답터
	 */
	private class SubCategoryListAdapter extends ArrayAdapter<String> 
	{
		public SubCategoryListAdapter(Context context, int textViewResourceId, ArrayList<String> list) 
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.normal_list_item, null);
			}
			
			String data = getItem(position);
			
			MilkTextView nameTextView = (MilkTextView) v.findViewById(R.id.normalItemNameTextView);
			
			nameTextView.setTextSize(TEXT_SIZE);
			nameTextView.setText(data);
			
			return v;
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_CATEGORY_INSERT);
		startActivity(intent);
	}

}
